package com.shensi.appCollect.controller;

import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.shensi.appCollect.pojo.AppUserInfo;
import com.shensi.appCollect.pojo.CouponUser;
import com.shensi.appCollect.constantEnum.Constant;
import com.shensi.appCollect.pojo.*;
import com.shensi.appCollect.pojo.dto.CardPasswordDto;
import com.shensi.appCollect.service.*;
import com.shensi.appCollect.utils.CodeMsg;
import com.shensi.appCollect.utils.ResultData;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.util.*;

/***
 * <Title> MemberController </Title>
 * <Description> 会员信息 </Description>
 * <Date>2021年10月28日</Date>
 */


@RestController
//@QuJiaRequest
@CrossOrigin
@Api(tags = "会员信息")
@Slf4j
public class MemberController {
    private static Logger logger =(Logger) LoggerFactory.getLogger(MemberController.class);
    @Resource
    private AppUserInfoService appUserInfoService;
    @Resource
    private EnterpriseService enterpriseService;
    @Resource
    private GradeService gradeService;
    @Resource
    private AppUserSuperDetailService appUserSuperDetailService;
    @Resource
    private AppUserSuperService appUserSuperService;
    @Resource
    private  CouponService couponService;

    @Autowired
    private ICardPasswordService cardPasswordService;
    @Autowired
    private IUserVirtualGradeRelService userVirtualGradeRelService;


    /*
     * 查询会员信息
     * @param unionId
     * @param enterpriseId
     * @return
     */
    @GetMapping(value = "/selectMemberInfo")
    @ApiOperation(value = "查询会员信息", httpMethod = "GET", notes = "查询会员信息")
    public String selectMemberInfo(@RequestParam String mobilePhone, @RequestParam Integer enterpriseId){
        logger.info("查询会员信息参数 mobilePhone：" + mobilePhone+ "; enterpriseId: "+ enterpriseId);
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        SimpleDateFormat fmt = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        ResultData resultData = null;
        AppUserInfo appUserInfos = appUserInfoService.getAppUserInfoAndBalance(AppUserInfo.builder().stationId(enterpriseId).mobilePhone(mobilePhone).build());
        if(null != appUserInfos){
            logger.info("会员信息：" + appUserInfos);
            appUserInfos.setGradeCode("0");
            appUserInfos.setGradeName("暂无");
            //获取会员等级
            List<Grade> gradeList = gradeService.selectGradeList(Grade.builder().deleteFlag("0").enterpriseId(Long.valueOf(enterpriseId.toString())).build());
            if(null != gradeList && gradeList.size() >0){
                for (Grade g : gradeList){
                    if(null != g.getGradeGrowValue()){
                        if(appUserInfos.getGrowUpValue() >= Integer.valueOf(g.getGradeGrowValue())){
                            appUserInfos.setGradeName(g.getGradeName());
                            appUserInfos.setGradeCode(g.getGradeCode());
                            break;
                        }
                    }
                }
            }
            List<AppUserSuperDetail> appUserSuperDetails = appUserSuperDetailService.selectAppUserSuperDetailList(AppUserSuperDetail.builder().userId(Long.valueOf(appUserInfos.getUserId()))
                    .enterpriseId(Long.valueOf(enterpriseId)).build());
            if(appUserSuperDetails != null && appUserSuperDetails.size() == 1){
                AppUserSuperDetail appUserSuperDetail = appUserSuperDetails.get(0);
                AppUserSuper appUserSuper = appUserSuperService.selectAppUserSuperById(appUserSuperDetail.getSuperId());
                if(appUserSuper != null){
                    Map<String,Object> superMap = new HashMap<String,Object>();
                    superMap.put("superId",appUserSuperDetail.getSuperId());
                    superMap.put("superName",appUserSuper.getSuperName());
                    superMap.put("endTime",fmt.format(appUserSuperDetail.getEndDate()));
                    if(appUserSuperDetail.getEndDate().before(new Date())){
                        superMap.put("status","0");
                    }else{
                        if(appUserSuperDetail.getEnable() == 0){
                            superMap.put("status","1");
                            appUserInfos.setGradeCode("s");
                            appUserInfos.setGradeName("超级会员");
                        }else{
                            superMap.put("status","0");
                        }
                    }
                    appUserInfos.setSuperInfo(superMap);
                }
            }
            getUserGrade(appUserInfos,gradeList);
            if (!StringUtils.equals("s",appUserInfos.getGradeCode())) {
                UserVirtualGradeRel virtualGradeRel = userVirtualGradeRelService.queryUserVirtualGrade(Long.valueOf(enterpriseId), Long.valueOf(appUserInfos.getUserId()), LocalDateTime.now());
                if (virtualGradeRel != null) {
                    appUserInfos.setGradeCode(virtualGradeRel.getGradeCode());
                    appUserInfos.setGradeName(Constant.GRADE_MAP.get(virtualGradeRel.getGradeCode()));
                }
            }
            appUserInfos.setCouponCount(0);
            Enterprise enterprise = enterpriseService.selectEnterpriseInfo(enterpriseId);
            if(null !=enterprise && "1".equals(enterprise.getCouponEnabledFlag())){
                appUserInfos.setCouponCount(couponService.setCoupnCount(mobilePhone,enterpriseId));
//                        couponService.selectCouUserSum(CouponUser.builder().mobilePhone(mobilePhone).enterpriseId(enterpriseId).couponIsUsed("0").build())
//                        couponService.selectCouUserCount();
            }

            List<CouponUser> allUserCoupons = couponService.selectUserAllCoupons(CouponUser.builder()
                    .mobilePhone(mobilePhone)
                    .enterpriseId(enterpriseId)
                    .couponIsUsed("0").build());
            appUserInfos.setCouponCount(allUserCoupons.size());
            resultData = ResultData.success(appUserInfos);
        }else {
            resultData = ResultData.success("");
        }
        return  gson.toJson(resultData);
    }

    private void getUserGrade(AppUserInfo appUserInfos,List<Grade> gradeList){
//        // 判断用户是否是超级会员
//        AppUserSuperDetail appUserSuperDetail = appUserSuperDetailService.selectAppUserSVIPInfoByCurrentTime(AppUserSuperDetail.builder()
//                .enterpriseId(Long.valueOf(appUserInfos.getStationId()))
//                .userId(Long.valueOf(appUserInfos.getUserId()))
//                .build());
//        if(Objects.nonNull(appUserSuperDetail)){
//            appUserInfos.setGradeCode("s");
//            appUserInfos.setGradeName("超级会员");
//            return;
//        }

        // 判断用户是否是黑卡 不是黑卡需要计算到达下一级还需要多少成长值
        if(!"s".equals(appUserInfos.getGradeCode()) && !"5".equals(appUserInfos.getGradeCode())){
            //判断用户的等级
            String gradeCode = appUserInfos.getGradeCode();
            String nextGradeCode = String.valueOf((Integer.parseInt(gradeCode) + 1));
            Integer gradeGrowValue = 0;
            for (Grade grade : gradeList) {
                if(nextGradeCode.equals(grade.getGradeCode())){
                    gradeGrowValue = grade.getGradeGrowValue();
                }
            }
            Integer missValue = gradeGrowValue - appUserInfos.getGrowUpValue();
            appUserInfos.setMissValue(missValue);
            appUserInfos.setNextGradeCode(nextGradeCode);
        }
    }

    /*
     * 更新会员信息
     * @param member
     * @return
     */
    @PostMapping(value = "/updateMemberInfo")
    @ApiOperation(value = "更新会员信息", httpMethod = "POST", notes = "更新会员信息")
    public String updateMemberInfo(@RequestBody AppUserInfo appUserInfo){
        Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create();
        ResultData resultData = null;
        if(StringUtils.isNotBlank(appUserInfo.getMobilePhone()) && null !=appUserInfo.getStationId()){
            appUserInfoService.updateAppUserInfo(appUserInfo);
            resultData = ResultData.success(CodeMsg.SUCCESS);
        }else {
            resultData = ResultData.error(CodeMsg.PARAMS_NUll, "油企ID和手机号不能为空");
        }
        return  gson.toJson(resultData);
    }

    /**
     * 查询 电子卡免密支付状态和密码
     * 同一个人在同一油企下 电子卡密码一致，不做区分
     * */
    @GetMapping("/select")
    @ApiOperation(value = "查询电子卡免密支付状态和密码", httpMethod = "GET",response = CardPasswordDto.class)
    public ResultData getCustomerElectronicCard(@RequestParam("enterpriseId") Integer enterpriseId,
                                                @RequestParam("mobilePhone") String mobilePhone){

        if(Objects.isNull(enterpriseId) || StringUtils.isEmpty(mobilePhone)){
            log.info("查询电子卡免密请求参数异常！enterpriseId:[{}],mobilePhone:[{}]",enterpriseId,mobilePhone);
            return ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        log.info("查询支付密码请求参数 enterpriseId:[{}],mobilePhone:[{}]",enterpriseId,mobilePhone);
        CardPasswordDto cardPasswordDto = cardPasswordService.selectCardPassword(enterpriseId, mobilePhone);
        return ResultData.success(cardPasswordDto);
    }

    /**
     * 修改电子卡免密支付状态和密码
     * */
    @PostMapping("/update")
    @ApiOperation(value = "修改电子卡免密支付状态和密码", httpMethod = "POST")
    public ResultData updateCustomerElectronicCard(@RequestBody CardPasswordDto cardPasswordDto){

        if(Objects.isNull(cardPasswordDto)){
            return ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        if(CollectionUtils.isEmpty(cardPasswordDto.getIds()) || StringUtils.isEmpty(cardPasswordDto.getPayPassword())){
            log.info("修改电子卡密码请求参数异常,cardPasswordDto:[{}]", JSONObject.toJSONString(cardPasswordDto));
            return ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        log.info("修改电子卡免密支付状态和密码 cardPasswordDto：[{}]",JSONObject.toJSONString(cardPasswordDto));
        cardPasswordService.updateCardPassword(cardPasswordDto);
        return ResultData.success();
    }

    /**
     * 只查询 电子卡免密支付状态
     * */
    @GetMapping("/selectfree")
    @ApiOperation(value = "只查询 电子卡免密支付状态", httpMethod = "GET",response = CardPasswordDto.class)
    public ResultData getCustomerElectronicCardFree(@RequestParam("enterpriseId") Integer enterpriseId,
                                                    @RequestParam("mobilePhone") String mobilePhone){

        if(Objects.isNull(enterpriseId) || StringUtils.isEmpty(mobilePhone)){
            log.info("查询电子卡免密请求参数异常！enterpriseId:[{}],mobilePhone:[{}]",enterpriseId,mobilePhone);
            return ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        log.info("查询电子卡免密状态请求参数 enterpriseId:[{}],mobilePhone:[{}]",enterpriseId,mobilePhone);
        CardPasswordDto cardPasswordDto = cardPasswordService.selectCardPassword(enterpriseId, mobilePhone);
        cardPasswordDto.setPayPassword(null);
        return ResultData.success(cardPasswordDto);
    }

    /**
     * 密码校验
     * */
    @PostMapping("/check")
    @ApiOperation(value = "密码校验", httpMethod = "POST")
    public ResultData checkCustomerElectronicCard(@RequestBody CardPasswordDto cardPasswordDto){

        if(Objects.isNull(cardPasswordDto)){
            return ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        if(CollectionUtils.isEmpty(cardPasswordDto.getIds()) || StringUtils.isEmpty(cardPasswordDto.getPayPassword())){
            log.info("修改电子卡密码请求参数异常,cardPasswordDto:[{}]", JSONObject.toJSONString(cardPasswordDto));
            return ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        log.info("密码校验请求参数 cardPasswordDto:[{}]",JSONObject.toJSONString(cardPasswordDto));
        Boolean result = cardPasswordService.checkCardPassword(cardPasswordDto);
        if(Boolean.TRUE.equals(result)){
            return ResultData.success(true);
        }
        return ResultData.error("支付密码错误，请重试",false);
    }

    /**
     * 密码校验(安卓pos)
     * */
    @PostMapping("/posCheck")
    @ApiOperation(value = "POS机密码校验", httpMethod = "POST")
    public ResultData posCheckCustomerElectronicCard(@RequestBody CardPasswordDto cardPasswordDto){

        if(Objects.isNull(cardPasswordDto)){
            return ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        if(CollectionUtils.isEmpty(cardPasswordDto.getIds()) || StringUtils.isEmpty(cardPasswordDto.getPayPassword())){
            log.info("电子卡id和密码请求参数异常,cardPasswordDto:[{}]", JSONObject.toJSONString(cardPasswordDto));
            return ResultData.error(CodeMsg.REQUEST_FAIL);
        }
        log.info("密码校验请求参数 cardPasswordDto:[{}]",JSONObject.toJSONString(cardPasswordDto));
        Boolean result = cardPasswordService.checkCardPassword(cardPasswordDto);
        if(Boolean.TRUE.equals(result)){
            return ResultData.success(true);
        }
        return ResultData.error(CodeMsg.PASSWORD_ERROR);
    }

}
